<template>
  <div class="document-create-title">
    <el-form label-position="top" :model="params" :rules="rules" ref="ruleForm">

      <el-form-item :label="`${$t('wiki.bulletin.create.textTitle.label1')}：`" class="create-item item-title" prop="rule">
        <el-input class="title" v-model="params.title" @blur="titleCheck"></el-input>
      </el-form-item>
      <p class="title-error" v-if="params.title && params.title.length > 100">{{$t('wiki.bulletin.create.textTitle.tips1')}}</p>
      <p class="title-error" v-if="msg && !params.title">{{$t('wiki.bulletin.create.textTitle.tips2')}}</p>

      <el-form-item :label="`${$t('wiki.bulletin.create.textTitle.label2')}：`" class="create-item" prop="typeId">
        <el-select v-model="params.typeId" class="search-type">
          <el-option v-for="item in params.options" :key="item.id" :value="item.id" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="`${$t('wiki.bulletin.create.textTitle.label3')}：`" class="create-item" prop="typeId">
        <div class="range">
          <span style="color: #999" v-if="params.selectedDepts.length > 0">{{$t('common.base.department')}}：
            <el-tag class="search-tag" closable @close="handleTags(tag, 'depts')" v-for="tag in params.selectedDepts" :key="tag.id">{{tag.name}}</el-tag>
          </span>
          <span style="color: #999; padding-left: 15px" v-if="params.selectedUsers.length > 0">{{$t('common.base.person')}}：
            <el-tag class="search-tag" closable @close="handleTags(tag, 'users')" v-for="tag in params.selectedUsers" :key="tag.userId">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="tag.staffId"></open-data>
              </template>
              <template v-else>
                {{tag.displayName}}
              </template>
            </el-tag>
          </span>
          <div class="icon-add-tags-btn" @click="chooseTeam">
            <i class="iconfont icon-jia icon-addTags"></i>
          </div>
        </div>
      </el-form-item>
      <p class="title-error" v-if="range">{{range}}</p>

      <el-form-item :label="`${$t('wiki.bulletin.create.textTitle.label4')}：`" class="create-item">
        <div class="file">
          <div class="base-comment-attachment base-file__preview file-item" v-if="params.form.attachments.length > 0">
            <base-file-item v-for="file in params.form.attachments" :Source="params.form.attachments" :key="file.id" :file="file" @delete="deleteFile" size="small"></base-file-item>
          </div>
          <button type="button" class="base-comment-tool file-button" @click="chooseFile">
            <i class="iconfont icon-attachment"></i> {{$t('wiki.bulletin.create.textTitle.btn1')}}
          </button> 
          <input type="file" ref="input" @change="handleChange" multiple>
          <div class="base-comment-cover loading" v-if="!allowOperate">
            <base-spin :text="$t('common.base.waiting')"></base-spin>
          </div>
        </div> 
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import * as TeamApi from '@src/api/TeamApi'
import platform from '@src/platform';
import Uploader from '@src/util/uploader';
import http from '@src/util/http';

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import i18n from '@src/locales'

export default {
  name: 'text-title',
  props: {
    value: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      isOpenData,
      params: this.value,
      inputVisible: false, // 添加标签input显示标识
      tagValue: '', // 添加的标签
      options: [], // 文章分类
      pending: false,
      msg: '',
      range: '',
      rules: {
        title: [
          { required: true, message: i18n.t('wiki.bulletin.create.textTitle.tips3'), trigger: 'blur' },
          { max: 100, message: i18n.t('wiki.bulletin.create.textTitle.tips4'), trigger: 'blur' }
        ],
        rule: [
          { required: true, message: i18n.t('wiki.bulletin.create.textTitle.tips5'), trigger: 'blur' },
        ],
        typeId: [
          { required: true, message: i18n.t('wiki.bulletin.create.textTitle.tips6'), trigger: 'change' }
        ],
        range: [
          { required: true, message: i18n.t('wiki.bulletin.create.textTitle.tips7'), trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 加载显示
    allowOperate(){
      return !this.pending
    }
  },
  methods: {
    // 点击加号显示标签输入框
    chooseTeam () {
      let max = -1;
      
      let options = {
        title: this.$t('wiki.bulletin.create.textTitle.tips8'),
        seeAllOrg: true,
        selectedUsers: this.params.selectedUsers,
        selectedDepartments: this.params.selectedDepts,
        isCanChooseRole: false,
        max,
        mode: BaseSelectUserModeEnum.Filter
      };
      
      return this.$fast.select.multi.all(options).then(result => {
        if(result.status == 0){
          let data = result.data || {};
          let users = data.users || [];
          let depts = data.depts || [];
          let serviceProviders = data.serviceProviders || [];

          this.params.selectedUsers = users;
          this.params.selectedDepts = depts.concat(serviceProviders);
          if(users.length > 0 || depts.length > 0) {
            this.range = false;
          }
          this.deftCheck();

          this.$el.dispatchEvent(new CustomEvent('form.validate', {bubbles: true}));
        }
      })
        .catch(err => console.error(err))
    },

    async deftCheck () {
      try {
        if(this.params.selectedDepts.length > 0) {
          let num = 0;
          this.params.selectedDepts.forEach(async item => {
            let params = {
              tagId: item.id,
              pageNum: 1,
              pageSize: 50,
              sellAllOrg: false,
              keyword: '',
            }
            let res = await TeamApi.userList(params)
            num = res.list.length + num;
            this.params.deptPerson = num;
          })
        }
      } catch (error) {
        console.error('error', error)
      }
      
    },

    // 添加标签，最多5个
    addTags () {
      if(this.tagValue) {
        this.params.tags.push(this.tagValue);
      }
      this.inputVisible = false;
      this.tagValue = '';
    },

    // 删除标签
    handleTags (tag, text) {
      if(text == 'users') {
        this.params.selectedUsers.splice(this.params.selectedUsers.indexOf(tag), 1);
      } else {
        this.params.selectedDepts.splice(this.params.selectedDepts.indexOf(tag), 1);
      }
    },

    // 选择文件
    handleChange(event){
      const files = event.target.files;
      if(!files || !files.length) return;

      let form = this.params.form;

      if(form.attachments.length + files.length > Uploader.FILE_MAX_NUM) {
        let message = this.$t('common.base.uploadModal.uploadCountTips', {count:Uploader.FILE_MAX_NUM});
        let max = 9 - form.attachments.length;

        if(max > 0 && files.length < 9){
          message += `, ${this.$t('common.base.uploadModal.canUploadCountTips', {count:max})}`;
        }

        return platform.alert(message)
      }

      this.pending = true;

      Uploader.batchUploadWithParse({files, action: '/files/upload/wiki', source: 'wiki'}).then(result => {
        let {success, error} = result;

        if(error.length > 0){
          let message = error.map(item => item.message).join('\n');
          //此处不能return
          platform.alert(message)
        }

        if(success.length > 0){
          form.attachments = form.attachments.concat(success);
        }
      })
        .catch(err => console.error(err))
        .then(() => this.pending = false)
    },

    // 触发inputclick事件选择文件
    chooseFile () {
      if(this.pending) return platform.alert(this.$t('common.base.uploadModal.tips1'));
      if(this.params.form.attachments.length >= Uploader.FILE_MAX_NUM) {
        return platform.alert(this.$t('common.base.uploadModal.uploadCountTips', {count:Uploader.FILE_MAX_NUM}));
      }
        
      this.$refs.input.value = null;
      this.$refs.input.click();
    },

    // 删除文件
    deleteFile(file) {
      let index = this.params.form.attachments.indexOf(file);
      if(index >= 0) {
        this.params.form.attachments.splice(index, 1);
      }
    },

    titleCheck() {
      this.msg = '';
      if(!this.params.title) {
        this.msg = this.$t('wiki.bulletin.create.textTitle.tips9');
        return false;
      }
      if(this.params.title.length > 100) {
        return false;
      }
      return true;
    },

    rangeCheck () {
      if(this.params.selectedUsers.length <= 0 && this.params.selectedDepts.length <= 0) {
        this.range = this.$t('wiki.bulletin.create.textTitle.tips10');
        return false;
      }
      return true;
    },
  }
}
</script>

<style lang="scss">
.document-create-title {
  background: #fff;

  .create-item {
    position: relative;
    width: 100%;
    padding-top: 10px;
    margin: 0;

    border-bottom: 1px solid #EBEBEB;

    .el-radio {
      line-height: 30px;

      .el-radio__label {
        font-size: 13px;
      }
    }

    .icon-permission {
      position: relative;
      top: 1px;

      font-size: 14px;
      margin-left: 4px;
    }

    .search-tag {
      margin-left: 4px;
      border: none;
      background: #E8EFF0;
      color: #606266;
      line-height: 24px;
    }

    .input-new-tag {
      display: inline-block;
      width: 80px;
    }

    .icon-add-tags-btn {
      display: inline-block;
      position: relative;
      top: 2px;
      width: 20px;
      height: 20px;
      line-height: 20px;

      margin-left: 5px;

      cursor: pointer;
      .icon-addTags {
        font-size: 14px;
        @include fontColor();
      }
    }
    
    input[type='file']{
      display: none !important;
    }

    .file {
      font-size: 0;
      .file-item {
        display: inline-flex;
        flex-wrap: wrap;

        vertical-align: middle;

        .base-file-info-name {
          max-width: 350px;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .file-button {
        vertical-align: middle;
        margin-left: 8px;
      }

      .loading {
        bottom: 10px;

        .base-spin-text {
          padding: 0;
        }
      }
    }

    .range {
      .notification-range {
        position: absolute;
        bottom: 0;
        z-index: -20;
        display: inline-block;
        width: calc(100% - 82px);
        border: none;

        .biz-team-select-tags {
          display: none;
        }
      }
    }

    .el-input__inner {
      border-color: #e0e1e2;
    }
    
    
  }

  .title-error {
    height: 17px;
    color: #f56c6c;
    font-size: 12px;
    line-height: 12px;
    margin: 0;
    padding-top: 5px;
  }

  .item-title {

    .el-form-item__content {

      input {
        border: none;
        width: calc(100% - 60px);
      }
    }

    .title {
      width: calc(100% - 65px);

      .el-input__inner {
        border: none;
      }
    }
  }
}
</style>